//
//  GKContent.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2018/9/10.
//  Copyright © 2018 wangws1990. All rights reserved.
//

import UIKit

class GKContent: HandyJSON {

    var bookId   :String = ""
    var chapterId:String = ""
    var title    :String = ""
    var content  :String = ""
    var created  :String = ""
    var updated  :String = ""
    
    var isVip    :Bool   = false

    var pageCount:Int{
        return self.pageArray.count
    }
    required init() {}
    
    func mapping(mapper: HelpingMapper) {
        mapper <<< self.chapterId <-- ["chapterId","id",]
        mapper <<< self.content   <-- ["cpContent","body","content"]
    }
    public lazy var pageArray: [NSAttributedString] = {
        return []
    }()
    public var empty :Bool{
        return self.content.count == 0
    }
    var getContent :String{
        return removeLine(content:content)
    }
    public func pageContent(){
        self.pageBound(BaseMacro.appFrame())
    }
    public func attContent(_ page :NSInteger) ->NSAttributedString{
        let index = page < 0 ? 0 : page
        if self.pageArray.count > index{
            return self.pageArray[index]
        }
        return NSAttributedString()
    }
    private func pageBound(_ bound:CGRect){
        self.pageArray.removeAll()
        let content = self.lineContent
        let defaultFont = GKBookSet.defaultFont()
        let attString = NSMutableAttributedString(string: content, attributes:defaultFont)
        let datas = content.components(separatedBy:moya.separated)
        if let title = datas.first {
            let strContent : NSString = content as NSString
            if strContent.contains(title) {
                let paragraphStyle  = NSMutableParagraphStyle()
                paragraphStyle.alignment = .center//两边对齐
                let range = strContent.range(of: title)
                attString.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
                attString.addAttribute(.font, value: moya.bookChapterFont, range:range)
            }
        }
        let lastAttString = attString
        let path = UIBezierPath(rect: bound)
        while lastAttString.string.count > 0{
            let frameSetter  = CTFramesetterCreateWithAttributedString(lastAttString)
            let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path.cgPath, nil)
            let range = CTFrameGetVisibleStringRange(frame)
            if lastAttString.length >= range.length + range.location{
                let att = lastAttString.attributedSubstring(from: NSRange(location: range.location, length: range.length))
                if att.string.count > 0 {
                    self.pageArray.append(att)
                }
                lastAttString.deleteCharacters(in: NSRange(location: range.location, length: range.length))
            }
        }
    }
    public var size : CGSize{
        let size = BaseMacro.appFrame().size
        return CGSize(width: size.width, height: size.height + 6)
    }
    public var lineContent :String{
        var content :String = self.content
        content = content.replacingOccurrences(of: "\n\r", with: "\n")
        content = content.replacingOccurrences(of: "\r\n", with: "\n")
        content = content.replacingOccurrences(of: "\n\n", with: "\n")
        content = content.replacingOccurrences(of: "\t\n", with: "\n")
        content = content.replacingOccurrences(of: "\t\t", with: "\n")
        content = content.replacingOccurrences(of: "\n\n", with: "\n")
        content = content.replacingOccurrences(of: "\r\r", with: "\n")
        content = content.trimmingCharacters(in: .whitespacesAndNewlines);
        content = self.removeLine(content: content);
        content = self.name + content
        return content
    }
    private var name :String{
        return self.title.count > 0 ? ("\n" + self.title + "\n\r") : ""
    }
    private func removeLine(content:String) ->String{
        var datas : NSArray = content.components(separatedBy: CharacterSet.newlines) as NSArray;
        let pre = NSPredicate(format:"self <> ''");
        datas = datas.filtered(using: pre) as NSArray
        var list : [String] = [];
        datas.forEach { (object) in
            if let str = object as? String{
                let strName = str.trimmingCharacters(in: .whitespacesAndNewlines)
                if strName.count > 0 {
                    let emptyData = "\u{3000}" + "\u{3000}" + strName
                    list.append(emptyData)
                }
            }
        }
        return list.joined(separator: "\n");
    }
}

